package com.mdsi.connection;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mdsi.db.Authenticator;
import com.mdsi.db.Authenticator.BadPassword;
import com.mdsi.db.Authenticator.NoUserFound;
import com.mdsi.models.Person;
import com.mdsi.models.Student;
import com.mdsi.models.Teacher;

/**
 * Servlet implementation class Index
 */
@WebServlet("/Connection")
public class Connection extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Connection() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (Boolean.valueOf(request.getParameter("fail"))) {
			this.getServletContext().setAttribute("redirect", true) ;
		}
		this.getServletContext().getRequestDispatcher("/WEB-INF/connection.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Person person = Authenticator.authenticate(request.getParameter("username"), request.getParameter("password")) ;
			HttpSession session = request.getSession(true) ;
			session.setAttribute("user", person) ;
			// session.setMaxInactiveInterval(24 * 31 * 3600) ;
			String part = (person instanceof Student) ? "Student" : ((person instanceof Teacher) ? "Teacher" : "Secretary") ;
			response.sendRedirect(request.getContextPath() + "/User/" + part) ;
			return ;
		}
		catch (SQLException e) {
			e.printStackTrace();
		} 
		catch (NoUserFound e) {
			this.getServletContext().setAttribute("nouser", true) ;
		} 
		catch (BadPassword e) {
			this.getServletContext().setAttribute("username", request.getParameter("username")) ;
		}
		this.getServletContext().getRequestDispatcher("/WEB-INF/connection.jsp").forward(request, response);
	}

}
